﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QueueUnlimited.API;
using System.Transactions;

namespace MultiplayerDice.Implementation.Processor
{
    internal static class EndedGamesProcessor
    {
        public static void Process(GenericEvent genericEvent)
        {
            var gameEnded = genericEvent.IsOfTypeOrNull<BusinessEvent.ExistingGameEndedEvent>();

            using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
            using (var database = new QueryDataStoreContext())
            {
                if (database.Query_EndedGames.Where(x => x.GameId == gameEnded.GameId)
                    .Count() == 0)
                {
                    database.Query_EndedGames.InsertOnSubmit(
                        new Query_EndedGame()
                        {
                            DateTimeOfEnded = gameEnded.DateTimeOfGameEnded,
                            GameId = gameEnded.GameId,
                            Player1Diced = gameEnded.Player1Diced,
                            Player1Name = gameEnded.Player1Name,
                            Player2Diced = gameEnded.Player2Diced,
                            Player2Name = gameEnded.Player2Name
                        });
                    database.SubmitChanges();
                }
            }
        }
    }
}
